package ma.android.oook;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TabHost.TabSpec;


public class NewItem extends Activity implements OnClickListener, OnItemSelectedListener{

	private static final String[] timeString = {
		"One day", "Two days","One week", "Two weeks", "One month", "Two months", "Six months"
    };
	private static final String OOOK_PREF_FILE="OookFile";

	private OookDbAdapter mDbHelper;
	private int [] selectedTagsCodes;
	private String [] selectedTagsNames;
	private long date;
	private TabHost tabs;
	private Intent parentIntent;
	private String operationType;
	private String contactId;
	private String mode;
	private int itemId;
	boolean firstTimeSelected;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.newitem);
        
        firstTimeSelected = true;
        
        tabs = (TabHost) findViewById(R.id.tabhost);
        tabs.setup();
        Context context=getBaseContext();
        
        Drawable money = context.getResources().getDrawable(R.drawable.money);
        TabSpec tab1 = tabs.newTabSpec(getString(R.string.money));
        tab1.setContent(R.id.tab1);
        tab1.setIndicator(getString(R.string.money),money);
        tabs.addTab(tab1);
        
        Drawable book = context.getResources().getDrawable(R.drawable.book_blue_open);
        TabSpec tab2 = tabs.newTabSpec(getString(R.string.book));
        tab2.setContent(R.id.tab2);
        tab2.setIndicator(getString(R.string.book),book);
        tabs.addTab(tab2);
        
        Drawable cd = context.getResources().getDrawable(R.drawable.cd_case);
        TabSpec tab3 = tabs.newTabSpec(getString(R.string.cd));
        tab3.setContent(R.id.tab2);
        tab3.setIndicator(getString(R.string.cd),cd);
        tabs.addTab(tab3);
        
        Drawable other = context.getResources().getDrawable(R.drawable.shopping_bag);
        TabSpec tab4 = tabs.newTabSpec(getString(R.string.other));
        tab4.setContent(R.id.tab2);
        tab4.setIndicator(getString(R.string.other),other);
        tabs.addTab(tab4);
        
        parentIntent = getIntent();
        mDbHelper = new OookDbAdapter(this);
        mDbHelper.open();
        
        Spinner reminderTime = (Spinner) findViewById(R.id.reminderSpinner);
        ArrayAdapter<String> remiderAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, timeString);
        remiderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        reminderTime.setAdapter(remiderAdapter);
        reminderTime.setOnItemSelectedListener(this);
        
        Button tags = (Button) findViewById(R.id.tagButton);
        tags.setOnClickListener(this);
        
        Button contacts = (Button) findViewById(R.id.contactsButton);
        contacts.setOnClickListener(this);
        
        Button accept = (Button) findViewById(R.id.acceptButton);
        accept.setOnClickListener(this);

        Button cancel = (Button) findViewById(R.id.cancelButton);
        cancel.setOnClickListener(this);
        
        operationType = parentIntent.getStringExtra(getString(R.string.operationType));
        mode = parentIntent.getStringExtra(getString(R.string.modeType));
        if (mode.equals(getString(R.string.editMode)))
        {
        	itemId = parentIntent.getIntExtra(getString(R.string.itemCod), 0);
        	loadFields(itemId);
        }
        mDbHelper.close();
        super.onCreate(savedInstanceState);  
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		Intent intent;
		Button pressed = (Button)v;
		
		switch(pressed.getId())
		{
			case R.id.acceptButton:		OookItem item = new OookItem();
										if (tabs.getCurrentTab()==0)
										{
											EditText amount = (EditText) findViewById(R.id.amountEdit);
											if (amount.getText().length() > 0)
												item.setAmount(Integer.parseInt(amount.getText().toString()));
											else
												item.setAmount(0);
								        	item.setDescription("");
								        }
								        else 
								        {
								        	EditText description = (EditText) findViewById(R.id.descriptionEdit);	
								        	item.setAmount(0);
								        	item.setDescription(description.getText().toString());
								        }
										item.setContactId(contactId);
										TextView contactName = (TextView) findViewById(R.id.selectedContactLabel);
										item.setContactName(contactName.getText().toString());
										item.setDeadlineDate(date);
										if(operationType.equals(getString(R.string.loan)))
											item.setLoan(true);
										else if (operationType.equals(getString(R.string.borrow)))
											item.setLoan(false);
										CheckBox position = (CheckBox)findViewById(R.id.locationCheck);
										if (position.isChecked());
										{
											LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
											Location location = locationManager.getLastKnownLocation("gps");
											if (location!=null)
											{
												item.setLatitude(location.getLatitude());
												item.setLongitude(location.getLongitude());
											}
											else
											{
												item.setLatitude(0);
												item.setLongitude(0);
											}
										}
										String itemType = tabs.getCurrentTabTag();
										item.setType(itemType);
										item.setTagCode(selectedTagsCodes);
										if (OookUtils.checkOookItem(item))
										{
											mDbHelper.open();
											if (mode.equals(getString(R.string.newMode)))
											{
												mDbHelper.saveItem(item);
											}
											else if (mode.equals(getString(R.string.editMode)))
											{
												item.setId(itemId);
												mDbHelper.updateItem(item);
											}
												
											mDbHelper.close();
											setResult(1);
											finish();
										}
										break;
									
			case R.id.contactsButton: 	intent = new Intent();
										intent.setAction(Intent.ACTION_GET_CONTENT);
										intent.setType("vnd.android.cursor.item/person");
										startActivityForResult(Intent.createChooser(intent, ""),1);
										break;
			
			case R.id.tagButton:		intent = new Intent(this,ListLabels.class);
										startActivityForResult(intent, 2);
										break;	
			
			case R.id.cancelButton:		finish();
										break;
		}
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{ 
		switch (requestCode)
		{
			case 1:	Uri uri= data.getData();
					ContentResolver cr= this.getContentResolver();
					Cursor c = cr.query(uri, new String[] {Contacts.People._ID,Contacts.People.NAME}, null, null, null);
					if (c!=null)
					{
						c.moveToFirst();
					    String name = c.getString(c.getColumnIndexOrThrow(Contacts.People.NAME));
					    contactId = c.getString(c.getColumnIndexOrThrow(Contacts.People._ID));
					    TextView selectedContact = (TextView)findViewById(R.id.selectedContactLabel);
					    selectedContact.setText(name);
					    c.close();
					}
					break;
					
				    
			case 2:	if (resultCode == 2)
					{	
						selectedTagsCodes = data.getIntArrayExtra(getString(R.string.selectedTagsCodes));
						selectedTagsNames = data.getStringArrayExtra(getString(R.string.selectedTagsNames));
						TextView selectedTagsLabel = (TextView) findViewById(R.id.selectedTagsLabel);
						selectedTagsLabel.setText(selectedTagsNames[0]);
						for (int i =1 ;i<selectedTagsNames.length;i++)
						{
							selectedTagsLabel.setText(selectedTagsLabel.getText() + "," + selectedTagsNames[i]);
						}
					}
					if (resultCode == 3)
					{
						Intent intent = new Intent(this,ListLabels.class);
						startActivityForResult(intent, 2);
					}
					break;
		}
	}
	
	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub
		if (!firstTimeSelected)
		{
			SharedPreferences preferences = getSharedPreferences(OOOK_PREF_FILE, MODE_PRIVATE);
			int dateType = preferences.getInt(getString(R.string.dateType), 0);
			
			Spinner reminder = (Spinner)findViewById(R.id.reminderSpinner);
			int position = reminder.getSelectedItemPosition();
			
			TextView selectedDateLabel = (TextView) findViewById(R.id.selectedDateLabel);
			
			date = OookUtils.calculateDeadLine(position);

			selectedDateLabel.setText(OookUtils.formatDate(date, dateType));
		}
		else
			firstTimeSelected = false;
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
	}
	
	private void loadFields(int itemId)
	{
		SharedPreferences preferences = getSharedPreferences(OOOK_PREF_FILE, MODE_PRIVATE);
		int dateType = preferences.getInt(getString(R.string.dateType), 0);
		OookItem item = getOookItem(itemId);
		if (item != null)
		{
			TextView contactName = (TextView) findViewById(R.id.selectedContactLabel);
			contactName.setText(item.getContactName());
			contactId = item.getContactId();
			String itemType = item.getType();
			for (int i = 0; i<tabs.getTabWidget().getChildCount();i++)
			{
				RelativeLayout rl= (RelativeLayout) tabs.getTabWidget().getChildAt(i);
				TextView t = (TextView) rl.getChildAt(1);
				if (itemType.equals(t.getText()))
				{
					if (i==0)
					{
						EditText amount = (EditText) findViewById(R.id.amountEdit);
						amount.setText(String.valueOf(item.getAmount()));
					}
					else
					{
						EditText description = (EditText) findViewById(R.id.descriptionEdit);
						description.setText(item.getDescription());
					}
					tabs.setCurrentTab(i);
					break;
				}
			}
			TextView selectedDateLabel = (TextView) findViewById(R.id.selectedDateLabel);
			date = item.getDeadlineDate();
			selectedDateLabel.setText(OookUtils.formatDate(item.getDeadlineDate(),dateType));
			if (item.getLatitude() != 0 && item.getLongitude()!= 0)
			{
				CheckBox location = (CheckBox) findViewById(R.id.locationCheck);
				location.setChecked(true);
				Button map = (Button)findViewById(R.id.mapButton);
				map.setOnClickListener(this);
				map.setVisibility(View.VISIBLE);
			}
			Cursor tagCodes = mDbHelper.findRelationByItemCode(item.getId());
			startManagingCursor(tagCodes);
			int [] codes = new int [tagCodes.getCount()];
			int i = 0;
			while (!tagCodes.isLast())
			{
				tagCodes.moveToNext();
				codes[i] = tagCodes.getInt(tagCodes.getColumnIndex("tag_id"));
				i++;
			}
			tagCodes.close();
			selectedTagsCodes = codes;
			Cursor tagDescriptions = mDbHelper.findTags();
			startManagingCursor(tagDescriptions);
			String [] descriptions = new String [codes.length];
			i=0;
			while (!tagDescriptions.isLast())
			{
				tagDescriptions.moveToNext();
				for (int n =0; n<codes.length;n++)
				{
					if (tagDescriptions.getInt(tagDescriptions.getColumnIndex("id"))== codes[n])
					{
						descriptions[i]=tagDescriptions.getString(tagDescriptions.getColumnIndex("description"));
						i++;
						break;
					}
				}
			}
			TextView selectedTagsLabel = (TextView) findViewById(R.id.selectedTagsLabel);
			selectedTagsLabel.setText(descriptions[0]);
			for (int n =1;n<descriptions.length;n++)
			{
				selectedTagsLabel.setText(selectedTagsLabel.getText() + "," + descriptions[n]);
			}
			tagDescriptions.close();
		}
	}

	private OookItem getOookItem(int itemId)
	{
		Cursor itemCursor = mDbHelper.findItem(itemId);
		startManagingCursor(itemCursor);
		OookItem item = null;
		if (itemCursor!= null)
		{
	    	startManagingCursor(itemCursor);
	    	itemCursor.moveToFirst();
			item = OookUtils.createItemFromCursor(itemCursor);
		}
		itemCursor.close();
		
		return item;
	}
}